# coding: utf-8

"""A wrapped logging module, this will generate a logger with
the caller module's name automaticly and set the level to debug.

1. to enjoy this, use this module like ``import utils.logger``
2. to avoid this, use this module like ``from utils.logger import Logger``

Recipe 1 is the same as
  >>> from utils.logger import Logger
  >>> log = Logger(__name__, "debug")

@author: TONE
@create: 2016-05-23
@update: 2016-06-02
"""

import logging


class Logger(object):

    __levels__ = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(self, name, level='debug'):
        self._logger = logging.getLogger(name)
        self._logger.setLevel(Logger.__levels__[level])
        self._datefmt = "%Y-%m-%d %H:%M:%S"
        self._fmt = "[%(levelname)8s] %(asctime)s <%(name)s> %(message)s"
        _console = logging.StreamHandler()
        _console.setLevel(logging.DEBUG)
        _formatter = logging.Formatter(self._fmt, self._datefmt)
        _console.setFormatter(_formatter)
        self._logger.addHandler(_console)

        self.d = self._logger.debug
        self.i = self._logger.info
        self.w = self._logger.warning
        self.e = self._logger.error
        self.c = self._logger.critical


def setup():
    """Set a logger in the caller module automaticly, use level "debug"
    as default, or you can change it below at any time you like
    """
    import inspect
    stack = inspect.stack()
    # 0: this-file, 1: this-func, 2-6: middleware-stuff * 5, 7: caller
    frame = stack[7].frame
    module = inspect.getmodule(frame)
    log = Logger(module.__name__, level="debug")
    log.d('logger "%s" has been generated automaticly' % module.__name__)
    frame.f_locals.update({'log': log})

setup()
